/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DialogAddBill.java
 *
 * Created on Jan 10, 2012, 1:35:19 PM
 */
package GUI;

import Model.BillDetailTableModel;
import Model.BillTableModel;
import Entity.Bill;
import Entity.BillDetail;
import Entity.Category;
import Entity.ConnectionSQL;
import Entity.Item;
import Entity.User;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.ResourceBundle;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;

/**
 *
 * @author Trung Duc
 */
public class DialogAddBill extends javax.swing.JDialog {
    private User user;
    private Bill bill;
    private ResourceBundle messages;
    private BillDetailTableModel model;
    private PanelBillManage parent;
    /** Creates new form DialogAddBill */
    public DialogAddBill(GUI.PanelBillManage parent, boolean modal,ResourceBundle messages,User user,Bill bill) {
        //super(parent,modal);
        this.parent = parent;
        this.messages = messages;
        this.user = user;
        this.bill = bill;
        initComponents();
        this.setLocationRelativeTo(parent);
        model = new BillDetailTableModel(messages);
        billDetailTable.setModel(model);
        setComboBoxCategory();
        setComboBoxItem(cbCategory.getSelectedItem().toString());
        billDetailTable.setAutoCreateRowSorter(true);
        billDetailTable.getTableHeader().setReorderingAllowed(false);
        billDetailTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        cbCategory.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setComboBoxItem(cbCategory.getSelectedItem().toString());
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtQuantity = new javax.swing.JFormattedTextField();
        jLabel2 = new javax.swing.JLabel();
        btnAdd = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        billDetailTable = new javax.swing.JTable();
        cbCategory = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        cbItem = new javax.swing.JComboBox();
        btnCreateBill = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        btnRemove = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Item");

        txtQuantity.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("######"))));

        jLabel2.setText("Quantity");

        btnAdd.setText("Add");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        billDetailTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(billDetailTable);

        cbCategory.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel3.setText("Category");

        cbItem.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        btnCreateBill.setText("Create Bill");
        btnCreateBill.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCreateBillActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnRemove.setText("Remove Item");
        btnRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(cbCategory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 214, Short.MAX_VALUE)
                        .addComponent(jLabel2))
                    .addComponent(cbItem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnAdd)
                        .addGap(67, 67, 67))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(txtQuantity, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 567, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(btnRemove)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 256, Short.MAX_VALUE)
                .addComponent(btnCreateBill)
                .addGap(27, 27, 27)
                .addComponent(btnCancel)
                .addGap(23, 23, 23))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtQuantity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(cbCategory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnAdd)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(cbItem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 241, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCreateBill)
                    .addComponent(btnCancel)
                    .addComponent(btnRemove))
                .addContainerGap(35, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        add();
    }//GEN-LAST:event_btnAddActionPerformed

    private void btnCreateBillActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCreateBillActionPerformed
        createBill();
    }//GEN-LAST:event_btnCreateBillActionPerformed

    private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveActionPerformed
        removeItem();
    }//GEN-LAST:event_btnRemoveActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        cancel();
    }//GEN-LAST:event_btnCancelActionPerformed
    /**
     * 
     */
    private void setComboBoxCategory(){
        cbCategory.removeAllItems();
        ConnectionSQL cnn = new ConnectionSQL(messages);
        List<Category> listCategory = cnn.getCategory();
        for(Category c : listCategory){
            cbCategory.addItem(c.getName());
        }
    }
    /**
     * 
     * @param categoryName 
     */
    private void setComboBoxItem(String categoryName){
        cbItem.removeAllItems();
        ConnectionSQL cnn = new ConnectionSQL(messages);
        List<Item> listItem = cnn.getItemByCategoryName(categoryName);
        for(Item i: listItem){
            cbItem.addItem(i.getName());
        }
    }
    /**
     * 
     */
    private void add(){
        if(txtQuantity.getText().equals("")) 
            JOptionPane.showMessageDialog(this, messages.getString("messagesQuantityNull"));
        else {
            ConnectionSQL cnn = new ConnectionSQL(messages);
            int quantity = Integer.parseInt(txtQuantity.getText());
            String itemName = cbItem.getSelectedItem().toString();
            String categoryName = cbCategory.getSelectedItem().toString();
            Item item = cnn.getItemByItemNameAndCategoryName(itemName, categoryName);
        if(item.getQuantity()<quantity)
                JOptionPane.showMessageDialog(this, messages.getString("messagesOverQuantity"));
        else{
            BillDetail bd = new BillDetail(bill.getId(), item.getId(), item.getName(),categoryName ,quantity, item.getPrice());
            if(model.AddBillDetail(bd)){
               cnn.addBillDetail(bd);
            }else{
                cnn.updateBillDetail(bd.getBillID(), bd.getItemID(), bd.getQuantity());
            }
            model.fireTableDataChanged();
        }
        }
    }
    private void createBill(){
       int i = JOptionPane.showConfirmDialog(this, messages.getString("messagesConfirmCreateBill"), messages.getString("titleConfirmCreateBill"), JOptionPane.YES_NO_OPTION);
       if(i == JOptionPane.OK_OPTION){
           parent.viewAllBill();
           parent.fireDataChange();
           JOptionPane.showMessageDialog(this, messages.getString("messagesCreateBillComplete"));
           this.dispose();
       }
    }
     private void removeItem() {
        int i = billDetailTable.getSelectedRow();
        if(i==-1 ) JOptionPane.showMessageDialog(this, messages.getString("messagesNoSelect"));
        else{
           int index = Integer.parseInt(billDetailTable.getValueAt(i,0).toString());
           model.removeBillDetail(index-1);
           model.fireTableDataChanged();
           int quantity = Integer.parseInt(billDetailTable.getValueAt(i,3).toString());
           String itemName = billDetailTable.getValueAt(i,1).toString();
           String categoryName = billDetailTable.getValueAt(i,2).toString();
           ConnectionSQL cnn = new ConnectionSQL(messages);
           Item item = cnn.getItemByItemNameAndCategoryName(itemName, categoryName);
           cnn.removeBillDetail(bill.getId(), item.getId(), quantity);
        }
    }
     
    private void cancel() {
        int i = JOptionPane.showConfirmDialog(this, messages.getString("messagesCancelBill"), messages.getString("titleCancelBill"), JOptionPane.YES_NO_OPTION);
        if(i == JOptionPane.OK_OPTION){
        List<BillDetail> listBillDetail = model.getListBillDetail();
        ConnectionSQL cnn = new ConnectionSQL(messages);
        for(BillDetail bd : listBillDetail){
            cnn.removeBillDetail(bd.getBillID(), bd.getItemID(), bd.getQuantity());
        }
        cnn.removeBill(bill.getId());
        parent.removeBill(bill.getId());
        parent.fireDataChange();
        this.dispose();
        }
    }
    /**
     * @param args the command line arguments
     */
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable billDetailTable;
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnCreateBill;
    private javax.swing.JButton btnRemove;
    private javax.swing.JComboBox cbCategory;
    private javax.swing.JComboBox cbItem;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JFormattedTextField txtQuantity;
    // End of variables declaration//GEN-END:variables



}
